package fr.gestionimmoejb.dao.ejb3;

import java.io.Serializable;
import java.util.List;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import fr.gestionimmoejb.dao.GenericDao;

public abstract class GenericDaoImpl <T, PK extends Serializable> implements GenericDao<T, PK> {
	
	protected final Log log = LogFactory.getLog(getClass());
	private Class<T> persistentClass;
	
	@PersistenceContext
    private EntityManager em;
	
	public GenericDaoImpl(){}
	
	public GenericDaoImpl(final Class<T> persistentClass) {
		log.debug("GenericDaoImpl init");
        this.persistentClass = persistentClass;
    }

	public boolean exists(PK id) {
		log.debug("exists " + id);
		if (this.get(id)!=null){
			return true;
		}
		return false;
	}

	public T get(PK id) {
		log.debug("get " + id);
		return em.find(persistentClass, id);
	}

	@SuppressWarnings("unchecked")
	public List<T> getAll() {
		log.debug("getAll ");
		return em.createQuery("from " + persistentClass.getName()).getResultList();
	}

	public void remove(PK id) {
		log.debug("remove " + id);
		em.remove(em.find(persistentClass, id));
		
	}
	
	public T save(T object) {
		log.debug("save " + object);
		return em.merge(object);
	}

	


}
